package com.wbs.lease.web.admin.custom.converter;

import com.wbs.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @author 韦帮愫
 * @version 1.0
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {


    //实现自定义类型转换工厂

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {

        return new Converter<String, T>() {
            @Override
            public T convert(String code) {
                //通过getEnumConstants获取所有枚举值（反射）
                T[] enumConstants = targetType.getEnumConstants();
                //遍历所有枚举值，和接收的code进行比较，如果相等，则返回该枚举值
                for (T enumConstant : enumConstants) {
                    if (enumConstant.getCode().equals(Integer.valueOf(code))) {
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("非法的枚举值:" + code);
            }
        };
    }
}
